﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using GlobalLib;

namespace GlobalLib.UI
{
    public class HttpUntity
    {
        public static T GetQueryString<T>(string name)
        {
            if (Util.IsStringNullOrEmpty(name)) 
              return default(T);

            string value = HttpContext.Current.Request.QueryString[name];
            return ConvertString2Anything<T>(value);
        }

        public static T GetFormValue<T>(string name)
        {
            if (Util.IsStringNullOrEmpty(name))
                return default(T);

            string value = HttpContext.Current.Request.Form[name];
            return ConvertString2Anything<T>(value);
        }

        public static T GetCookieValue<T>(string name)
        {
            if (Util.IsStringNullOrEmpty(name))
                return default(T);

            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if(cookie == null)
                return default(T);

            if (Util.IsStringNullOrEmpty(cookie.Value))
                return default(T);

            string value = cookie.Value;
            return ConvertString2Anything<T>(value);
        }

        private static T ConvertString2Anything<T>(string value) {
            if (Util.IsStringNullOrEmpty(value))
                return default(T);

            T result;
            try
            {
                result = (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception ex)
            {
                //logging
                throw ex;
            }

            return result;
        }
    }
}
